<template>
    <a-card title="费用管理" style="width: 800px;pointer-events: all;">
        <template #extra>
            <a-select v-model:value="selectedBuilding" style="width: 150px" @change="handleBuildingChange">
                <a-select-option v-for="building in buildings" :key="building.value" :value="building.value">
                    {{ building.label }}
                </a-select-option>
            </a-select>
        </template>
        <div style="margin-bottom: 12px;">
            <a-select v-model:value="filterStatus" style="width: 120px;" size="small">
                <a-select-option value="all">全部</a-select-option>
                <a-select-option value="paid">已缴费</a-select-option>
                <a-select-option value="unpaid">未缴费</a-select-option>
            </a-select>
        </div>
        <a-table size="small" bordered :data-source="filteredFeeData" :columns="columns" :pagination="pagination"
            @change="handleTableChange">
            <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'doorNumText'">
                    <a-tag color="red">{{ record.doorNumText }}</a-tag>
                </template>
                <template v-if="column.dataIndex === 'is_paid'">
                    <a-tag :color="record.is_paid ? 'green' : 'red'">
                        {{ record.is_paid ? '已缴费' : '未缴费' }}
                    </a-tag>
                </template>
                <template v-if="column.key === 'action'">
                    <a-space>
                        <a-button type="link" @click="handleEdit(record)">编辑</a-button>
                        <a-button v-if="!record.is_paid" type="link" @click="handlePay(record)">缴费</a-button>
                    </a-space>
                </template>
            </template>
        </a-table>
    </a-card>

    <a-modal v-model:open="modalVisible" title="编辑费用信息" @ok="handleModalOk" @cancel="handleModalCancel">
        <a-form :model="formState" ref="formRef" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
            <a-form-item label="水费" name="water_fee">
                <a-input-number v-model:value="formState.water_fee" :min="0" :precision="2" style="width: 100%"
                    placeholder="请输入水费" />
            </a-form-item>
            <a-form-item label="电费" name="electric_fee">
                <a-input-number v-model:value="formState.electric_fee" :min="0" :precision="2" style="width: 100%"
                    placeholder="请输入电费" />
            </a-form-item>
            <a-form-item label="物业费" name="property_fee">
                <a-input-number v-model:value="formState.property_fee" :min="0" :precision="2" style="width: 100%"
                    placeholder="请输入物业费" />
            </a-form-item>
            <a-form-item label="缴费状态" name="is_paid">
                <a-switch v-model:checked="formState.is_paid" />
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { getBuildings, getUnitsByBuilding, getHouseholdsByUnit, updateHouseholdFee, payHouseholdFee } from '@/api/api'
// 1. 状态变量定义
const buildings = ref([])   // 楼栋列表
const feeData = ref([])     // 费用数据
const selectedBuilding = ref(null)  // 选中的楼栋
const modalVisible = ref(false)     // 弹窗显示状态
const formRef = ref(null)           // 表单引用
const filterStatus = ref('all')     // 筛选状态

// 表单状态对象
const formState = reactive({
    id: null,
    water_fee: 0,
    electric_fee: 0,
    property_fee: 0,
    is_paid: false,
})

// 分页配置
const pagination = reactive({
    total: 0,
    current: 1,
    pageSize: 8,
    size: 'small',
    showSizeChanger: false,
    showQuickJumper: false
})

// 表格列配置（包含总费用计算）
const columns = [
    { title: '门牌号', dataIndex: 'doorNumText', key: 'doorNumText', align: 'center' },
    { title: '业主姓名', dataIndex: 'owner_name', key: 'owner_name', align: 'center' },
    { title: '水费', dataIndex: 'water_fee', key: 'water_fee', align: 'center' },
    { title: '电费', dataIndex: 'electric_fee', key: 'electric_fee', align: 'center' },
    { title: '物业费', dataIndex: 'property_fee', key: 'property_fee', align: 'center' },
    {
        title: '总费用',
        dataIndex: 'total_fee',
        key: 'total_fee',
        align: 'center',
        //customRender: 针对表格单个单元格
        customRender: ({ record }) => {
            const total = (Number(record.water_fee) || 0) +
                (Number(record.electric_fee) || 0) +
                (Number(record.property_fee) || 0);
            //保留两位小数
            return total.toFixed(2);
        }
    },
    { title: '缴费状态', dataIndex: 'is_paid', key: 'is_paid', align: 'center' },
    { title: '操作', key: 'action', align: 'center' }
]

// 初始化加载楼栋列表
onMounted(async () => {
    try {
        const buildInfo = await getBuildings()
        if (buildInfo?.code === 200) {
            buildings.value = buildInfo.data.map(item => ({
                value: item.id,
                label: item.name
            }))
        }
    } catch (error) {
        message.error('获取楼栋列表失败')
    }
})

// 楼栋选择和费用数据加载
const handleBuildingChange = (value) => {
    selectedBuilding.value = value
    // 加载该楼栋的数据
    fetchFeeData(value)
}

const fetchFeeData = async (buildingId) => {
    try {
        const unitsRes = await getUnitsByBuilding(buildingId)
        if (unitsRes?.code === 200) {
            // 存储所有费用数据
            const allFees = []
            for (const unit of unitsRes.data) {
                //获取每个单元的住户信息
                const householdsRes = await getHouseholdsByUnit(unit.id)
                if (householdsRes?.code === 200) {
                    const fees = householdsRes.data.map(item => ({
                        ...item,// 保留原有数据
                        // 生成门牌号：楼层号+单元号（补零）
                        doorNumText: `${item.floor_num}${unit.number.toString().padStart(2, '0')}`,
                        // 生成用于排序的数值
                        sortKey: Number(`${item.floor_num}${unit.number.toString().padStart(2, '0')}`)
                    }))
                    //添加到总数组
                    allFees.push(...fees)
                }
            }
            //最终数据赋值给表格
            feeData.value = allFees.sort((a, b) => a.sortKey - b.sortKey)
            pagination.total = allFees.length
        }
    } catch (error) {
        message.error('获取费用数据失败')
    }
}

// 费用状态筛选
const filteredFeeData = computed(() => {
    // 如果选择"全部"，直接返回原始数据
    if (filterStatus.value === 'all') return feeData.value
    // 否则根据支付状态筛选
    return feeData.value.filter(item => filterStatus.value === 'paid' ? item.is_paid : !item.is_paid)
})

// 费用编辑功能
const handleEdit = (record) => {
    formState.id = record.id
    formState.water_fee = record.water_fee
    formState.electric_fee = record.electric_fee
    formState.property_fee = record.property_fee
    formState.is_paid = record.is_paid
    modalVisible.value = true
}

const handleModalOk = async () => {
    try {
        const submitData = {
            water_fee: Number(formState.water_fee),
            electric_fee: Number(formState.electric_fee),
            property_fee: Number(formState.property_fee),
            is_paid: Boolean(formState.is_paid)
        }

        const res = await updateHouseholdFee(formState.id, submitData)
        if (res.code === 200) {
            message.success('保存成功')
            modalVisible.value = false
            //在本地数据中查找要更新的记录          
            const index = feeData.value.findIndex(item => item.id === formState.id)
            //如果找到了记录，更新本地数据         
            feeData.value[index] = {
                ...feeData.value[index],// 展开原有的所有数据
                ...submitData// 展开新数据，用展开运算符会覆盖同名属性
            }
        }
    } catch (error) {
        message.error('保存失败')
    }
}

const handleModalCancel = () => {
    modalVisible.value = false
}

// 缴费操作
const handlePay = async (record) => {
    try {
        //等待缴费 API 调用完成
        const res = await payHouseholdFee(record.id)
        if (res.code === 200) {
            message.success('缴费成功')
            // 查找要更新的数据
            const index = feeData.value.findIndex(item => item.id === record.id)
            // 更新缴费状态
            feeData.value[index].is_paid = true
        }
    } catch (error) {
        message.error('缴费失败')
    }
}

// 分页处理
const handleTableChange = (pag) => {
    pagination.current = pag.current
    pagination.pageSize = pag.pageSize
}
</script>

<style scoped>
:deep(.ant-table-tbody > tr > td) {
    padding: 4px 8px;
    height: 32px;
}

:deep(.ant-table-thead > tr > th) {
    padding: 4px 8px;
    height: 32px;
}
</style>